package com.li.shop.controller;

import com.li.shop.domain.*;
import com.li.shop.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private ShopCardService shopCardService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private UserAdressService userAdressService;

    /**
     * 点击结算按钮生成订单展示数据到订单页面
     *
     */



//
//    @RequestMapping(value="/usradrlist",method= RequestMethod.GET)
//    public String listUsrAdr(Model model){
//        List<UserAdress> list = userAdressService.findAll();
//        //System.out.println(list.get(0).getLiuYans().get(0).getLiucontent());
//        //System.out.println(list.get(0).getDate());
//        model.addAttribute("list", list);
//        //System.out.println(list.size());
//        //System.out.println(list);
//
//        return "/before/paybak";
//    }


//    @RequestMapping(value="/useradrlist",method= RequestMethod.GET)
//    public String listuseradr(Model model, HttpSession session){
//        User user=(User)session.getAttribute("user");
//        String id=user.getuId();
//        List<UserAdress> list = userAdressService.findAllAdr(id);
//        model.addAttribute("list", list);
//        return "before/paybak";
//    }



    @RequestMapping(value="/orderlist",method= RequestMethod.GET)//账单明细
    public String listOrder(Model model, HttpSession session){
        float allMoney = 0;
        User user=(User)session.getAttribute("session_user");
        String id=user.getuId().toString();
        List<Orders> ordersList=orderService.findAllOrders(id);
        System.out.println(ordersList.get(0).getAddress());
        System.out.println(ordersList.get(0).getProduct().getMoney());
        for(Orders orders :ordersList){
             allMoney = allMoney+orders.getProduct().getMoney();
        }
        System.out.println(allMoney);
        //List<Orders>ordersList=orderService.findAllOrders(id);
        model.addAttribute("ordersList",ordersList);
        model.addAttribute( "id",id);
        model.addAttribute("allMoney",allMoney);
//        System.out.println(ordersList.get(0).getAddress());
//        System.out.println(ordersList.get(0).getuId());
//        System.out.println(ordersList.get(0).getProduct().getMoney());
        return "/before/person/bill";
    }
    @RequestMapping(value="/orderlist1",method= RequestMethod.GET)//查看具体账单明细
    public String listOrder1(Model model, HttpSession session){
        float money=0;
        User user=(User)session.getAttribute("session_user");
        String id=user.getuId().toString();
        List<Orders> ordersList1=orderService.findAllOrders1(id);//查看具体账单
        for(Orders orders :ordersList1){
            Product product=orders.getProduct();
            product.setMoney((-1)*product.getMoney());
        }
        //List<Orders>ordersList=orderService.findAllOrders(id);
        model.addAttribute("ordersList1",ordersList1);
        model.addAttribute( "id",id);
        System.out.println(ordersList1.get(0).getAddress());
        System.out.println(ordersList1.get(0).getuId());
        System.out.println(ordersList1.get(0).getProduct().getMoney());
        return "/before/person/billlist";
    }

    @RequestMapping(value = "/made", method = RequestMethod.GET)
    public String made(Model model, HttpSession session) {
        //得到当前用户的id
        String id=session.getAttribute("id").toString();
        System.out.println("wwwwww"+id);
        //根据u_id查出所有的p_id、pnum、p.*展示
        List<Shopcard> shopcards = shopCardService.searchgoods(id);
        double sum = 0;
        int num = 0;
        for (int i = 0; i < shopcards.size(); i++) {
            num += Integer.parseInt(shopcards.get(i).getPnum());
            sum += Integer.parseInt(shopcards.get(i).getPnum()) * shopcards.get(i).getProducts().get(0).getDazhe();
        }
        //根据u_id拿到所有的优惠券
        List<Coupon> coupons=couponService.find(id);
        for(Coupon coupon:coupons){
            System.out.println(coupon.getDiscount()+coupon.getContent());
        }

        //根据session中的id查询当前的用户的信息
        User user = userService.searchById(id);
        model.addAttribute("num", num);
        model.addAttribute("sum", sum);
        model.addAttribute("user", user);
        model.addAttribute("shopcard", shopcards);
        model.addAttribute("coupon",coupons);


        System.out.println("ddd"+id);
        //String id=session.getAttribute("id").toString();
        List<UserAdress> list = userAdressService.findAll( id);
        //System.out.println(list.get(0).getAdrId());
        model.addAttribute("list", list);


        return "/before/pay";
    }


    /**
     * 实现使用新地址的功能
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpSession session, @RequestParam("user-name") String name,
                       @RequestParam("user-phone") String phone,
                       @RequestParam("user-intro") String address) {

        System.out.println(name + phone + address);
        String id = (session.getAttribute("id")).toString();
        User user = new User();
        user.setUserName(name);
        user.setuId(id);
        user.setAddress(address);
        user.setPhone(phone);
        userService.update(user);
        return "redirect:/order/made";
    }

    /**
     * 编辑改地址信息
     */
    @RequestMapping(value = "edits", method = RequestMethod.GET)
    public String edits(@RequestParam("id") String id, Model model) {
        //根据id回显所有的内容
        User user = userService.searchById(id);
        model.addAttribute("user1", user);
        return "redirect:/order/made";
    }

    /**
     * 提交订单,将订单信息保存到order表中,然后重定向到订单页面
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String hand(HttpSession session,Model model,
                       @RequestParam("message") String content,
                       @RequestParam("se")String discount,
                       @RequestParam("check")String check) {
        //拿到当前的session中的id ，将id和o_id保存起来
        String id = session.getAttribute("id").toString();
        System.out.println("拿到的优惠券为"+discount);
        session.setAttribute("discount",discount);
        System.out.println("拿到的配送方式为"+check);
        //将当前的配送方式金额放到session中
        session.setAttribute("peisong",check);


        Date date = new Date();
        //拿到该用户现有的p_id
        List<Shopcard> shopcards = shopCardService.searchproduct(id);
        for (Shopcard s : shopcards) {
            User user = new User();
            user = userService.searchById(id);
            Orders orders = new Orders();
            orders.setuId(id);
            orders.setMessage(content);
            orders.setPeisong("圆通");
            orders.setDate(date);
            orders.setPnum(s.getPnum());
            //将该商品的支付状态
            orders.setPaymentStaus("1");
            orders.setDelivery("1");
            orders.setpId(s.getpId());
            orders.setUname(user.getUserName());
            orders.setAddress(user.getAddress());
            orderService.save(orders);
        }

        model.addAttribute("youhui",discount);
        return "redirect:/order/made";
    }

    /**
     * 稍后支付，生成同样的订单但是它的支付状态为0：未支付可以在自己的订单管理页面进行支付
     * */
    @RequestMapping(value = "/save1", method = RequestMethod.POST)
    @ResponseBody
    public String hand1(HttpSession session,Model model,
                        @RequestParam("message") String content,
                        @RequestParam("se")String discount,
                        @RequestParam("check")String check) {
        System.out.println("我是稍后支付功能");
        //拿到当前的session中的id ，将id和o_id保存起来
        String id = session.getAttribute("id").toString();
        System.out.println("拿到的优惠券为"+discount);
        session.setAttribute("discount",discount);
        System.out.println("拿到的配送方式为"+check);
        //将当前的配送方式金额放到session中
        session.setAttribute("peisong",check);

        Date date = new Date();
        //拿到该用户现有的p_id
        List<Shopcard> shopcards = shopCardService.searchproduct(id);
        for (Shopcard s : shopcards) {
            User user = new User();
            user = userService.searchById(id);
            Orders orders = new Orders();
            orders.setuId(id);
            orders.setMessage(content);
            orders.setPeisong("圆通");
            orders.setDate(date);
            orders.setPnum(s.getPnum());
            //将该商品的支付状态
            orders.setPaymentStaus("0");
            orders.setDelivery("0");
            orders.setpId(s.getpId());
            orders.setUname(user.getUserName());
            orders.setAddress(user.getAddress());
            orderService.save(orders);
        }

        model.addAttribute("youhui",discount);
        return "OK";
    }

    /**
     * 提交订单成功,显示支付的金额
     */
    @RequestMapping(value = "/success", method = RequestMethod.GET)
    public String success(Model model, HttpSession session) {
        //根据session中的id查询当前的用户的信息
        String id = (session.getAttribute("id").toString());
        //根据u_id查出所有的p_id、pnum、p.*展示
        List<Shopcard> shopcards = shopCardService.searchgoods(id);
        double sum = 0;
        int salesVolume=0;     //用于计算商品销量、杨
        for (int i = 0; i < shopcards.size(); i++) {
            sum += Integer.parseInt(shopcards.get(i).getPnum()) * shopcards.get(i).getProducts().get(0).getDazhe();
            System.out.println("支付成功的订单费用为"+sum);
            //            System.out.println("======="+shopcards.get(i).getpId()+"  ,  "+Integer.valueOf(shopcards.get(i).getPnum())+"==========");     //乱入，杨煦瑞写的用于测试的语句
            productService.updateSalesVolume(shopcards.get(i).getpId(),Integer.valueOf(shopcards.get(i).getPnum()));    //调用了更新销量方法，第一个参数是商品id，第二个参数是商品销售的数量

        }
        //得到当前session中的优惠券的值
        int discount=Integer.parseInt(session.getAttribute("discount").toString());
        //得到session中的配送费
        int peisong=Integer.parseInt(session.getAttribute("peisong").toString());

        User user = userService.searchById(id);
        model.addAttribute("sum", sum-discount+peisong);
        model.addAttribute("user", user);
        model.addAttribute("shopcard", shopcards);
        return "/before/success";
    }

    /**
     * 删除订单
     */
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(Model model, HttpSession session, @RequestParam("id") String id) {
        //根据传过来的P_id删除这个订单中的商品
        orderService.delete(id);
        //重定向到订单展示页面
        return "redirect:/product/ordershow";
    }

    /**
     * 一键支付
     */
    @RequestMapping(value = "/pay", method = RequestMethod.GET)
    public String pay(Model model, HttpSession session, @RequestParam("id") String oid) {
        System.out.println("oid为"+oid);
        //根据传过来的id将商品的payments设置为1
        String uid = session.getAttribute("id").toString();

        Orders orders=new Orders();
        orders.setoId(oid);
        orders.setuId(uid);
        orderService.updateByPid(orders);
        return "redirect:/product/ordershow";
    }



    @RequestMapping("order_list")
    public String list (Model model,@RequestParam("name")String name,@RequestParam("peisong")String peisong,@RequestParam("address")String address)
    {
        List<Orders>orders=orderService.list(name,peisong,address);
        model.addAttribute("orders",orders);
        return "back/product-list3";
    }
    @RequestMapping("order_listbefore")
    public String listbefore (Model model)
    {
        List<Orders>orders=orderService.list();
        model.addAttribute("orders",orders);
        return "back/product-list2";
    }

    @RequestMapping (value = "/deleteorderm",method=RequestMethod.GET)//查看订单支出明细（删除订单支出）
    //@ResponseBody//需要返回json数据 @RequestParam("id") @PathVariable("id")
    public String deleteOrderm(@RequestParam("id") String id, HttpSession session) {
        //var mymessage = confirm("确认删除嘛？");
        //if (mymessage == true) {
        int deleted = orderService.deleteOrdermByPrimaryKey(id);
        User user=(User) session.getAttribute("session_user");
        // return deleted > 0;
        //return "redirect:/backadminuser/searchuser";
        return "redirect:/order/orderlist1";//get请求可以使用重定向
        //return "/before/pay";
        //return "redirect:/backadminuser/deleteuser";
    }

}
